package com.zahb.qadx.ui.fragment;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.model.TrainAllBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.adapter.TrainTaskAdapter;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class TrainTaskListFragment extends BaseFragmentExt implements OnRefreshListener {
//123

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.ll_empty)
    LinearLayoutCompat llEmpty;

    private TrainTaskAdapter mTaskAdapter;
    private List<TrainAllBean.TaskListBean> list = new ArrayList<>();

    public int classid;

    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Override
    protected int getLayout() {
        return R.layout.fragment_train_task_list;
    }

    @Override
    protected void initViews(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(this);

        //updateData(list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mTaskAdapter = new TrainTaskAdapter(getActivity(),list);
        mRecyclerView.setAdapter(mTaskAdapter);
    }

    private boolean mFirstLoad = true;

    @Override
    public void onResume() {
        super.onResume();
        if (mFirstLoad) {
            mFirstLoad = false;
            showSkeleton();
        }
        onRefresh(mRefreshLayout);
    }

    private void updateData(List<TrainAllBean.TaskListBean> list) {
        this.list.clear();
        this.list.addAll(list);
        mTaskAdapter.notifyDataSetChanged();
        isVisible(mTaskAdapter.getItemCount() > 0);
    }

    private void isVisible(boolean flag){
        if (mRecyclerView.getAdapter() instanceof TrainTaskAdapter) {
            if(flag){
                mRecyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            }else{
                llEmpty.setVisibility(View.VISIBLE);
                mRecyclerView.setVisibility(View.GONE);
            }
        }
    }

    private final int topMargin = DisplayUtil.dip2px(16f);

    private RecyclerView.ItemDecoration mItemDecoration = new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            if (parent.getAdapter() == null) return;
            outRect.setEmpty();
            outRect.top = topMargin;
        }
    };

    private void showSkeleton() {
        mRefreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(mRecyclerView)
                .adapter(mTaskAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_task_skeleton)
                .show();
        mRecyclerView.addItemDecoration(mItemDecoration);
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                mRefreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                mRecyclerView.removeItemDecoration(mItemDecoration);
                isVisible(mTaskAdapter.getItemCount() > 0);
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    private void getTrainDetailsList() {
        addDisposable(RetrofitService.getNetService()
                .getTrainDetailsList(classid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMore();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if(response.getData().getTaskList()!=null&&response.getData().getTaskList().size()>0){
                            updateData(response.getData().getTaskList());
                        }
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                    hideSkeleton();
                }, throwable -> {
                    throwable.printStackTrace();
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMore();
                    Tips.RequestError(getActivity());
                    hideSkeleton();
                }));

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getTrainDetailsList();
    }
}
